import { defineStore } from 'pinia';
import { ref, reactive, computed } from 'vue';
import type { Transmission } from '@/common_ts/bo/WebSocketUpload';

import { MAX_CONCURRENT } from "@/common_js/common_variable"

export const useTaskQueue = defineStore('taskQueue', () => {
  /* 任务池：taskId -> Transmission */
  const queue = reactive(new Map<string, Transmission>());

  const runningTasks  = ref<Set<string>>(new Set()) // 正在跑的 md5

  const paused = ref(false);

  // 计算属性
  // /* 当前可用“坑位” */
  const freeSlots = computed(() => MAX_CONCURRENT - runningTasks.value.size)
  /* 所有待上传任务（status 0 或 4）*/
  const pendingList = computed(() =>
    [...queue.values()].filter(t => t.status === 0 || t.status === 4)
  )


  // 方法
  /* 新增 / 覆盖 */
  function add(item: Transmission) {
    queue.set(item.md5, { ...item, status: 0 });
    console.log('新增数据');
  }

  /* 删除 */
  function remove(md5: string) { queue.delete(md5); }

  /* 暂停 / 继续 */
  function doPause()  { paused.value = true; console.log("队列已经暂停"); }
  function doResume() { paused.value = false; console.log("队列已经恢复"); }


  return {
    queue,
    paused,
    runningTasks,
    freeSlots,
    pendingList,
    add,
    remove,
    doPause,
    doResume
  }
});